package cn.stylefeng.guns.modular.controller;

import cn.stylefeng.guns.base.consts.ConstantsContext;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RequestMapping("upload")
@RestController
public class UploadFileController {

    /**
     * 上传图片
     */
    @RequestMapping
    public ResponseData uploadImageResource(MultipartFile file) {
        String obsAk = ConstantsContext.getObsAk();
        String obsSk = ConstantsContext.getObsSk();
        String obsEndPoint = ConstantsContext.getObsEndPoint();
        /* 创建OBS客户端 */
        ObsClient obsClient = new ObsClient(obsAk, obsSk, obsEndPoint);
        try {
            final String keySuffixWithSlash = "system/";
            PutObjectResult putObjectResult = obsClient.putObject("wbs-bucket", keySuffixWithSlash + UUID.randomUUID() + ".jpg", file.getInputStream());
            return ResponseData.success(putObjectResult.getObjectUrl());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                obsClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ResponseData.error("失败");
    }

    /**
     * 上传富文本图片
     */
    @RequestMapping("rich")
    public Map<String, Object> uploadLayEditImageResource(MultipartFile file) {
        String obsAk = ConstantsContext.getObsAk();
        String obsSk = ConstantsContext.getObsSk();
        String obsEndPoint = ConstantsContext.getObsEndPoint();
        /* 创建OBS客户端 */
        ObsClient obsClient = new ObsClient(obsAk, obsSk, obsEndPoint);
        try {
            final String keySuffixWithSlash = "rich-text/";
            PutObjectResult putObjectResult = obsClient.putObject("wbs-bucket", keySuffixWithSlash + UUID.randomUUID() + ".jpg", file.getInputStream());
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("code", 0);
            returnMap.put("msg", "成功");
            Map<String, Object> data = new HashMap<>();
            data.put("src", putObjectResult.getObjectUrl());
            returnMap.put("data", data);
            return returnMap;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                obsClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
